package com.jsy.search.controller;

import com.alibaba.fastjson.JSON;
import com.github.wxpay.sdk.WXPayUtil;
import com.jsy.common.constant.StatusCode;
import com.jsy.common.vo.Result;
import com.jsy.search.service.WeixinPayService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/weixin/pay")
public class WeixinPayController {

    @Autowired
    private WeixinPayService weixinPayService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Value("${mq.pay.exchange.order}")
    private String orderExchange;

    @Value("${mq.pay.routing.key}")
    private String orderRoutingKey;

    @Value("${mq.pay.routing.seckillkey}")
    private String seckillOrderRoutingKey;


    /**
     * 创建支付二维码链接
     *
     * @param requestParamMap 请求参数：包含内容如下 outTradeNo订单号 money支付金额
     * @return 操作结果
     */
    @GetMapping("/create/native")
    public Result<Map<String, String>> createNative(@RequestParam Map<String, String> requestParamMap) {
        Map<String, String> map = weixinPayService.createNative(requestParamMap);
        return new Result<>("创建二维码链接成功", map);
    }

    /**
     * 查看支付状态
     *
     * @param outTradeNo 订单号
     * @return 操作结果
     */
    @GetMapping("/query/status")
    public Result<Map<String, String>> queryStatus(String outTradeNo) {
        Map<String, String> map = weixinPayService.queryStatus(outTradeNo);
        return new Result<>("查询订单成功！", map);
    }

    /**
     * 用户支付之后，微信支付系统的回调(回调内容为xml)
     * 微信支付系统会发送支付的结果到这个方法（使用postman模拟回调）
     *
     * @param request 请求对象
     * @return 微信可接受的xml返回结果
     */
    @RequestMapping("/callback")
    public String callback(HttpServletRequest request) {
        try {
            ServletInputStream inputStream = request.getInputStream();
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = inputStream.read(buffer)) != -1) {
                bos.write(buffer, 0, len);
            }
            String xmlStr = new String(bos.toByteArray(), "UTF-8");
            bos.close();
            inputStream.close();
            System.out.println("从微信返回的回调信息" + xmlStr);
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xmlStr);
            System.out.println("从微信返回的回调信息" + resultMap);

            HashMap<String, String> returnMap = new HashMap<>();
            returnMap.put("return_code", "SUCCESS");
            resultMap.put("return_msg", "OK");
            String xml = WXPayUtil.mapToXml(returnMap);
            //接收到信息后，需要处理订单，删除redis缓存信息，更新到数据库中，使用MQ处理
            //判断订单是否为秒杀类型
            String routingKey = orderRoutingKey;
            if (resultMap.containsKey("attach")) {
                String attach = resultMap.get("attach");
                Map<String, String> attachMap = JSON.parseObject(attach, Map.class);
                if ("seckill".equals(attachMap.get("type"))) {
                    routingKey = seckillOrderRoutingKey;
                }
            }
            rabbitTemplate.convertAndSend(orderExchange, routingKey, JSON.toJSONString(resultMap));
            return xml;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 根据订单号关闭微信支付系统的订单
     * @param outTradeNo 订单号
     * @return 操作结果
     */
    @GetMapping("/close/order")
    public Result<Map<String,String>> closeOrder(String outTradeNo){

        try {
            Map<String,String> map=weixinPayService.closeOrder(outTradeNo);
            return new Result<>("关闭订单成功",map);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result<>(false, StatusCode.ERROR,"关闭订单失败");
    }

}
